package com.wsc.wisdomchina.activitity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.util.Base64;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.wsc.wisdomchina.R;
import com.wsc.wisdomchina.Tools.AbPermissionUtils;
import com.wsc.wisdomchina.Tools.JsonTools;
import com.wsc.wisdomchina.Tools.Tools;
import com.wsc.wisdomchina.activitity.baseactivity.BaseActivity;
import com.wsc.wisdomchina.callback.ContributorView;
import com.wsc.wisdomchina.constant.Constant;
import com.wsc.wisdomchina.javaBean.MyModuleInfo;
import com.wsc.wisdomchina.javaBean.RespObj;
import com.wsc.wisdomchina.presenter.ContributorPresenter;
import com.wsc.wisdomchina.view.MyToast;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.lang.ref.SoftReference;
import java.util.List;

import de.hdodenhof.circleimageview.CircleImageView;

public class PersonInfoActivity extends BaseActivity implements View.OnClickListener,ContributorView{
    private RelativeLayout bottom_content_one, bottom_content_two, bottom_content_three, bottom_content_four;
    private ImageView regist_back;
    private TextView nicker_name, tv_addr, chang_phone,tv_headtitle;
    private CircleImageView head_icon;
    private Context context;
    private String myMoudleInfoString;
    private PopupWindow popupWindow;
    private View mpopupWindowView;
    private TextView tv_cancel;
    private TextView tv_takephoto;
    private TextView tv_photo;
    private ContributorPresenter contributorPresenter;
    private String uid;
    private final String MY_MODULE_UPLOAD_PIC_FLAG="MY_MODULE_UPLOAD_PIC_FLAG";
    private MyToast myToast;
    private Bitmap photo;
    private Bitmap initBitmap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.personinfo_layout);
        context = this;
        myToast=new MyToast(context);
        uid= Tools.getSharedPreferencesStrings(Constant.SharePreferenceUserid,"",context);
        contributorPresenter = new ContributorPresenter(this, context);
        iniView();
        initPopupWindow();

        AbPermissionUtils.requestPermissionsResult(this, 1
                , new String[]{
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                }
                , new AbPermissionUtils.OnPermissionListener() {
                    @Override
                    public void onPermissionGranted() {
                        initData();
                    }

                    @Override
                    public void onPermissionDenied() {

                    }
                });

    }

    private void iniView() {
        regist_back = (ImageView) findViewById(R.id.regist_back);
        tv_headtitle=(TextView) findViewById(R.id.tv_headtitle);
        tv_headtitle.setText("个人资料");
        bottom_content_one = (RelativeLayout) findViewById(R.id.bottom_head);
        head_icon = (CircleImageView) findViewById(R.id.head_icon_person);
        bottom_content_two = (RelativeLayout) findViewById(R.id.bottom_content_two);
        nicker_name = (TextView) findViewById(R.id.nicker_name);
        bottom_content_three = (RelativeLayout) findViewById(R.id.bottom_content_three);
        bottom_content_four = (RelativeLayout) findViewById(R.id.bottom_content_four);
        tv_addr = (TextView) findViewById(R.id.tv_addr);
        chang_phone = (TextView) findViewById(R.id.chang_phone);
        regist_back.setOnClickListener(this);
        bottom_content_one.setOnClickListener(this);
        bottom_content_two.setOnClickListener(this);
        bottom_content_three.setOnClickListener(this);
        bottom_content_four.setOnClickListener(this);
    }

    /**
     * 初始化popupwindow
     */
    private void initPopupWindow() {
        mpopupWindowView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.headinfo, null);
        popupWindow = new PopupWindow(mpopupWindowView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);// 全屏显示，将内容设置在底部
        popupWindow.setFocusable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());

        tv_cancel = (TextView) mpopupWindowView.findViewById(R.id.tv_cancel);
        tv_cancel.setOnClickListener(this);
        tv_takephoto = (TextView) mpopupWindowView.findViewById(R.id.tv_takephoto);
        tv_takephoto.setOnClickListener(this);
        tv_photo = (TextView) mpopupWindowView.findViewById(R.id.tv_photo);
        tv_photo.setOnClickListener(this);
    }

    private void initData() {
        myMoudleInfoString = Tools.getSharedPreferencesStrings(Constant.SharePreferenceMyModuleInfo, "", context);
        try {
            MyModuleInfo myModuleInfo = JsonTools.jsonStringToObject(myMoudleInfoString, MyModuleInfo.class);
            if (myModuleInfo != null) {
                nicker_name.setText(myModuleInfo.getUname());
                tv_addr.setText(myModuleInfo.getAddr());
                chang_phone.setText(myModuleInfo.getPhone());
                File file = new File(new File(Environment.getExternalStorageDirectory(), Constant.wsc_photo), "userid" + uid + ".jpg");
                if (file.exists()) {
                    initBitmap = BitmapFactory.decodeFile(file.getPath());
                    if (initBitmap != null) {
                        SoftReference<Bitmap> softbitmap = new SoftReference<Bitmap>(initBitmap);
                        if (softbitmap != null && softbitmap.get() != null) {
                            Drawable drawable = new BitmapDrawable(softbitmap.get());
                            head_icon.setImageDrawable(drawable);
                        }
                    }

                } else {
                    Glide.with(context).load(myModuleInfo.getPurl())
                            .diskCacheStrategy(DiskCacheStrategy.ALL)
                            .placeholder(R.mipmap.own_pic_logout)
                            .into((ImageView) head_icon);
                }
            }
        } catch (Exception e) {

        }

    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.regist_back:
                finish();
                break;
            case R.id.bottom_head:
                if (!popupWindow.isShowing()) {
                    popupWindow.showAtLocation(findViewById(R.id.bottom_head), Gravity.BOTTOM, 0, 0);// 在屏幕居中，无偏移
                } else {
                    popupWindow.dismiss();
                }
                break;
            case R.id.bottom_content_two:
                Intent intent_nicker_name = new Intent(context, ChangeNickerNameActivity.class);
                intent_nicker_name.putExtra("nickname", nicker_name.getText().toString());
                startActivityForResult(intent_nicker_name, 3);
                break;
            case R.id.bottom_content_three:
                Intent intent_phone_num = new Intent(context, ChangePhoneNumActivity.class);
                intent_phone_num.putExtra("phone", chang_phone.getText().toString().trim());
                startActivityForResult(intent_phone_num, 4);
                break;
            case R.id.bottom_content_four:
                Intent intentaddress=new Intent(context,AddressListAvtivity.class);
                startActivity(intentaddress);
//                Intent intent_change_arr = new Intent(context, ChangeAddressAvtivity.class);
//                intent_change_arr.putExtra("address", tv_addr.getText().toString().trim());
//                startActivityForResult(intent_change_arr, 5);
                // 取消点击事件
            case R.id.tv_cancel:
                popupWindow.dismiss();
                break;
            // 拍照点击事件
            case R.id.tv_takephoto:
                popupWindow.dismiss();
                try {
                    AbPermissionUtils.requestPermissionsResult(this, 1
                            , new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
                                    Manifest.permission.READ_EXTERNAL_STORAGE,
                            }
                            , new AbPermissionUtils.OnPermissionListener() {
                                @Override
                                public void onPermissionGranted() {

                                    Uri uri = getUri();
                                    Intent intent = new Intent();
                                    //添加这一句表示对目标应用临时授权该Uri所代表的文件
                                    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                                    intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);//设置Action为拍照
                                    intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);//将拍取的照片保存到指定URI
                                    startActivityForResult(intent,6);
                                }

                                @Override
                                public void onPermissionDenied() {

                                }
                            });
                }catch (Exception e)
                {
                    myToast.showShort("拍照失败");
                }
                break;
            // 用户相册点击事件
            case R.id.tv_photo:
                popupWindow.dismiss();
                try{
                    AbPermissionUtils.requestPermissionsResult(this, 1
                            , new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
                                    Manifest.permission.READ_EXTERNAL_STORAGE,
                            }
                            , new AbPermissionUtils.OnPermissionListener() {
                                @Override
                                public void onPermissionGranted() {
                                    Intent intentphoto = new Intent(Intent.ACTION_PICK, null);
                                    intentphoto.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                                    startActivityForResult(intentphoto, 1);
                                }

                                @Override
                                public void onPermissionDenied() {

                                }
                            });
                }catch (Exception e)
                {
                    myToast.showShort("读取相册失败");
                }
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            // 从相册里面获取
            case 1:
                if (data != null && data.getData()!=null)
                    startPhotoZoom(data.getData());
                break;
            // 裁剪
            case 2:
                if (data != null) {
                    setPicToView(data);
                }
                break;
            case 3:
                if (resultCode == 0) {
                    if(data!=null)
                        nicker_name.setText(data.getStringExtra("nickname"));
                }
                break;
            case 4:
                if (resultCode == 0) {
                    if(data!=null)
                        chang_phone.setText(data.getStringExtra("phone"));
                }
                break;
            case 5:
                if (resultCode == 0)
                {
                    if(data!=null)
                        tv_addr.setText(data.getStringExtra("addr"));
                }
                break;
            // 拍照
            case 6:
                startPhotoZoomCut();
                break;
        }
    }

    private Uri getUri() {
        try{
            File cacheDir;
            if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
                cacheDir = new File(android.os.Environment.getExternalStorageDirectory(), Constant.wsc_photo);
            else
                cacheDir = context.getCacheDir();
            if (!cacheDir.exists())
                cacheDir.mkdirs();

            File path = new File(cacheDir, "");
            if (!path.exists()) {
                path.mkdirs();
            }
            File file = new File(path, "takephoto.jpg");
            //由于一些Android 7.0以下版本的手机在剪裁保存到URI会有问题，所以根据版本处理下兼容性
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                return FileProvider.getUriForFile(context, "com.wsc.wisdomchina.fileprovider", file);
            } else {
                return Uri.fromFile(file);
            }
        }catch (Exception e)
        {
            return null;
        }

    }


    /**
     * @param uri
     * @Description 裁剪图片
     * @author jaily.zhang
     */
    private void startPhotoZoom(Uri uri) {
        try {
                 /*
         * 至于下面这个Intent的ACTION是怎么知道的，大家可以看下自己路径下的如下网页
		 * yourself_sdk_path/docs/reference/android/content/Intent.html
		 * 直接在里面Ctrl+F搜：CROP ，之前小马没仔细看过，其实安卓系统早已经有自带图片裁剪功能, 是直接调本地库的，小马不懂C C++
		 * 这个不做详细了解去了，有轮子就用轮子，不再研究轮子是怎么 制做的了...吼吼
		 */
            Intent intent = new Intent("com.android.camera.action.CROP");
            intent.setDataAndType(uri, "image/*");
            // 下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
            intent.putExtra("crop", "true");
            // aspectX aspectY 是宽高的比例
            intent.putExtra("aspectX", 1);
            intent.putExtra("aspectY", 1);
            // outputX outputY 是裁剪图片宽高
            intent.putExtra("outputX", 150);
            intent.putExtra("outputY", 150);
            intent.putExtra("return-data", true);
            startActivityForResult(intent, 2);
        }catch (Exception e)
        {

        }
    }

    /**
     * 裁剪图片从拍照
     */
    private void startPhotoZoomCut()
    {
        try {
            Uri uri = getUri();
            Intent intent = new Intent("com.android.camera.action.CROP");
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);

            intent.setDataAndType(uri , "image/*");
            intent.putExtra("crop", "true");
            intent.putExtra("aspectX", 1);
            intent.putExtra("aspectY", 1);
            intent.putExtra("outputX", 150);
            intent.putExtra("outputY", 150);
            intent.putExtra("scale", true);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, getUri());
            intent.putExtra("return-data", true);
            intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
            intent.putExtra("noFaceDetection", true);

            //将存储图片的uri读写权限授权给剪裁工具应用
            List<ResolveInfo> resInfoList = getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
            for (ResolveInfo resolveInfo : resInfoList) {
                String packageName = resolveInfo.activityInfo.packageName;
                grantUriPermission(packageName, uri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
            }
            startActivityForResult(Intent.createChooser(intent, "选择剪裁工具"), 2);
        } catch (Exception e) {

        }
    }

    /**
     * 保存裁剪之后的图片数据
     *
     * @param picdata
     */
    private void setPicToView(Intent picdata) {
        Bundle extras = picdata.getExtras();
        Uri data = picdata.getData();
        if (extras != null) {
            photo = extras.getParcelable("data");
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            if (photo != null) {
                try {
                    // Drawable drawable = new BitmapDrawable(photo);

                    /**
                     * 下面注释的方法是将裁剪之后的图片以Base64Coder的字符方式上 传到服务器，QQ头像上传采用的方法跟这个类似
                     */

                    int options = 70;
                    photo.compress(Bitmap.CompressFormat.JPEG, options, stream);
                    byte[] b = stream.toByteArray();// 将图片流以字符串形式存储下来
                    // 大于2KB
                    while (b.length > 5 * 1024) {
                        stream.reset();// 清空流
                        options -= 10;
                        photo.compress(Bitmap.CompressFormat.JPEG, options, stream);
                        b = stream.toByteArray();
                    }
                    String result = Base64.encodeToString(b, Base64.DEFAULT);
                    contributorPresenter.getUploadPic(uid,result,MY_MODULE_UPLOAD_PIC_FLAG);

                }catch (Exception e)
                {

                }finally {
                    try {
                        // 关闭流
                        stream.flush();
                        stream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

            }

        }
        //  htc 7.0  会出现   Bundle extras = picdata.getExtras();  extras 为空
        else if (extras == null && data != null) {
            try {
                photo = MediaStore.Images.Media.getBitmap(context.getContentResolver(), data);
                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                if (photo != null) {
                    try {
                        // Drawable drawable = new BitmapDrawable(photo);
                        /**
                         * 下面注释的方法是将裁剪之后的图片以Base64Coder的字符方式上 传到服务器，QQ头像上传采用的方法跟这个类似
                         */
                        int options = 70;
                        photo.compress(Bitmap.CompressFormat.JPEG, options, stream);
                        byte[] b = stream.toByteArray();// 将图片流以字符串形式存储下来
                        // 大于2KB
                        while (b.length > 5 * 1024) {
                            stream.reset();// 清空流
                            options -= 10;
                            photo.compress(Bitmap.CompressFormat.JPEG, options, stream);
                            b = stream.toByteArray();
                        }
                        String result = Base64.encodeToString(b, Base64.DEFAULT);
                        contributorPresenter.getUploadPic(uid,result,MY_MODULE_UPLOAD_PIC_FLAG);

                    }catch (Exception e)
                    {

                    }finally {
                        try {
                            // 关闭流
                            stream.flush();
                            stream.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onLoadContributorStart(String flag) {

    }

    @Override
    public void onLoadContributorSuccess(String jsonString, String flag) {
        try {
            //发送验证码
            if (flag.equals(MY_MODULE_UPLOAD_PIC_FLAG)) {
                RespObj respObj = JsonTools.jsonStringToObject(jsonString, RespObj.class);
                String code=respObj.getCode();
                if(code.equals("10300"))
                {
                    myToast.showShort("上传图片失败");
                }else if(code.equals("10700"))
                {
                    myToast.showShort("操作失败");
                }else if(code.equals("200") && respObj.getMessage()!=null)
                {
                    Drawable drawable = new BitmapDrawable(photo);
                    // 往SD卡里写入数据
                    Tools.WriteImaToSdcard(context, photo, Constant.wsc_photo, "userid" + uid + ".jpg");
                    head_icon.setImageDrawable(drawable);
                }
            }
        } catch (Exception e) {
        }
    }

    @Override
    public void onLoadContributorComplete(String flag) {
    }

    @Override
    public void onLoadContributorError(String error,String flag) {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (photo != null && !photo.isRecycled()) {
            photo.recycle();
            photo = null;
        }
        if (initBitmap != null && !initBitmap.isRecycled()) {
            initBitmap.recycle();
            initBitmap = null;
        }
    }

}
